package common;

import java.sql.*;

public class Dbutil {
	
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	
	private static final String className = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/shixun?characterEncoding=utf-8";
	private static final String user = "root";
	private static final String password = "123456";
   
	public Dbutil(){
		try {
			Class.forName(className);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Connection getConnection(){
		try {
			conn = DriverManager.getConnection(url,user,password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	public Statement setStatement(){
		try {
			if(conn == null){
			getConnection();
			}
			stmt = conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stmt;
	}
    
	public int executeUpdate(String sql){
		int result = -1;
		try {
			if(stmt == null){
			setStatement();
			}
			result = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public ResultSet executeQuery(String sql){
		try {
			if(stmt == null){
			setStatement();
			}
			rs = stmt.executeQuery(sql);	
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	
	public void closeDB(){
		try{
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();
			}
			if(conn != null){
				conn.close();
			}
		}catch(SQLException e){
			
		}
	}
}
